using Cysharp.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityGameFramework.Runtime;

namespace DTFramework.WebRequest
{
    [DisallowMultipleComponent]
    [AddComponentMenu("DTFramework/Web Request")]
    public sealed class WebRequestComponent : GameFrameworkComponent
    {
        /// <summary>
        /// 游戏框架组件初始化。
        /// </summary>
        protected override void Awake()
        {
            base.Awake();
        }

        /// <summary>
        /// Get 请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">配置</param>
        /// <returns></returns>
        public async UniTask<string> RequestGet(string url)
            => await RequestGet(url, null);

        /// <summary>
        /// Post 请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="jObject">请求消息头-json 对象</param>
        /// <returns></returns>
        public async UniTask<string> RequestPost(string url, JObject jObject)
            => await RequestPost(url, jObject.ToString(), null);
        /// <summary>
        /// Post 请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求消息头</param>
        /// <returns></returns>
        public async UniTask<string> RequestPost(string url, string postData)
            => await RequestPost(url, postData, null);

        /// <summary>
        /// Post 请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="jObject">请求消息头-json 对象</param>
        /// <returns></returns>
        public async UniTask<string> RequestPost(string url, JObject jObject, Dictionary<string, string> headers)
        {
            return await RequestPost(url, jObject.ToString(), headers);
        }
        /// <summary>
        /// Get 请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">配置</param>
        /// <returns></returns>
        public async UniTask<string> RequestGet(string url, Dictionary<string, string> headers)
        {
            string result = null;
            using (UnityWebRequest request = new UnityWebRequest(url, "GET"))
            {
                //设置请求消息格式
                request.SetRequestHeader("Content-Type", "application/json");

                if (headers != null)
                {
                    foreach (var keyPair in headers) request.SetRequestHeader(keyPair.Key, keyPair.Value);
                }
                await request.SendWebRequest();

                if (request.result == UnityWebRequest.Result.Success)
                {
                    result = request.downloadHandler.text;
                    return result;
                }
                else
                {
                    Debug.LogError("==> WebRequest Get 失败：" + request.downloadHandler.text);
                }
            }
            return result;
        }

        /// <summary>
        /// Post 请求数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求消息头</param>
        /// <param name="headers">配置</param>
        /// <returns></returns>
        public async UniTask<string> RequestPost(string url, string postData, Dictionary<string, string> headers)
        {
            string result = null;
            using (UnityWebRequest request = new UnityWebRequest(url, "POST"))
            {
                byte[] postBytes = new UTF8Encoding(false).GetBytes(postData);

                request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
                request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                //设置请求消息格式
                request.SetRequestHeader("Content-Type", "application/json");

                if (headers != null)
                {
                    foreach (var keyPair in headers) request.SetRequestHeader(keyPair.Key, keyPair.Value);
                }
                await request.SendWebRequest();

                if (request.result == UnityWebRequest.Result.Success)
                {
                    result = request.downloadHandler.text;
                    return result;
                }
                else
                {
                    Debug.LogError("==> WebRequest Post 失败：" + request.downloadHandler.text);
                }
            }
            return result;
        }
    }
}
